package com.smashcrush.server;

import java.util.HashMap;
import java.util.Map;

import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.ResourceHandler;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.webapp.WebAppContext;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.servlet.DispatcherServlet;

public class SmashCrushServer {

	public static void main(String[] args) {

		Server server = new Server(8080);
		// server.setHandler(handler);
		try {

			WebAppContext webapp = new WebAppContext();
	        webapp.setContextPath("/");
	        webapp.setWar("/home/joe/smashcrush/server/war");
			
	        server.setHandler(webapp);
			
			ResourceHandler resource_handler = new ResourceHandler();
			resource_handler.setWelcomeFiles(new String[] { "index.html" });
			resource_handler.setResourceBase("/home/joe/smashcrush/server/war");
			
			ServletContextHandler context = new ServletContextHandler(
					ServletContextHandler.SESSIONS);

			context.setWelcomeFiles(new String[] { "index.html" });

			context.setContextPath("/");
			context.setResourceBase("/home/joe/smashcrush/server/war");
			Map<String, String> params = new HashMap<String, String>();
			params.put("contextConfigLocation",
					"classpath:com/smashcrush/server/applicationContext.xml");
			context.setInitParams(params);

			ServletHolder holder = new ServletHolder();
			DispatcherServlet dispatcherServlet = new DispatcherServlet();
			holder.setServlet(dispatcherServlet);
			holder
					.setInitParameter("contextConfigLocation",
							"classpath:com/smashcrush/server/applicationContext-servlet.xml");
			holder.setInitOrder(1);
			context.addServlet(holder, "/api/*");

			ContextLoaderListener contextLoader = new ContextLoaderListener();
			context.addEventListener(contextLoader);

			ContextHandlerCollection contexts = new ContextHandlerCollection();
			contexts.setHandlers(new Handler[] { new DefaultHandler(), context,
					resource_handler });

			webapp.setHandler(contexts);
			
			server.start();
			server.join();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
